﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace WindowsFormsApp_g2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string id = textBox1.Text;
            string pattern = @"^\d{17}(\d|X)$";
            if(!Regex.IsMatch(id,pattern))
            {
                label2.Text = "不合法";
                textBox2.Text = "身份证号格式有误";
            }
            else
            { 
                int year = Convert.ToInt32(id.Substring(6, 4));
                int month = Convert.ToInt32(id.Substring(10, 2));
                int day = Convert.ToInt32(id.Substring(12, 2));
                try
                {
                    DateTime time = new DateTime(year, month, day);
                }
                catch (Exception)
                {
                    label2.Text = "不合法";
                    textBox2.Text = "出生日期有误";
                    //textBox2.AppendText("出生日期有误\r\n");
                }
                //int[] arr = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };//加权数组
                //string[] id_check = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };//校验数组 
                //int sum = 0;
                //for(int i = 0; i < 17; i++)
                //{
                //    sum += int.Parse(id[i].ToString()) * arr[i];
                //}
                //int result = sum % 11;
                //if (id_check[result]==id[17].ToString())
                //{
                //    label2.Text = "合法";
                //    textBox2.Text = "身份证号格式,出生日期，校验码均无误";
                //}
                int sum = 0;
                for(int i = 2; i < 19; i++)
                {
                    sum += (int.Parse(id[18-i].ToString()) * (int)Math.Pow(2, i-1));
                }
                int result = (12 - sum %11 ) % 11;
                if (int.Parse(id[17].ToString()) == result||(id[17].ToString()=="X"&&result==10))
                {
                    label2.Text = "合法";
                    textBox2.Text = "身份证号格式,出生日期，校验码均无误";
                }
                else
                {
                    label2.Text = "不合法";
                    textBox2.AppendText("\r\n校验码有误");
                }
            }
        }
    }
}
